package com.baitiaojun.security.config;

import com.baitiaojun.security.core.filter.JwtAuthenticationFilter;
import com.baitiaojun.security.core.handler.AuthDeniedHandler;
import com.baitiaojun.security.core.handler.AuthFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.CorsFilter;

//EnableGlobalMethodSecurity注解开启方法级别安全控制,
//prePostEnabled在接口访问前后校验, 开启 @PreAuthorize 和 @PostAuthorize 两个注解
//securedEnabled根据角色权限进行校验, , 开启 @Secured注解
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig {

    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Autowired
    private AuthFailureHandler authFailureHandler;

//    @Autowired
//    private LogoutHandler logoutHandler;

    @Autowired
    private FilterRegistrationBean<CorsFilter> corsFilter;

    @Autowired
    private AuthDeniedHandler authDeniedHandler;

    /**
     * 配置加密对象进行密码加密校验
     * @return
     */
    @Bean
    public PasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置认证对象进行用户登陆认证
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    /**
     * security规则配置
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http.csrf().disable() //不使用session, 关闭CSRF保护, token的作用就是用于防范csrf攻击
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //不使用session获取securityContext
                .and().exceptionHandling().authenticationEntryPoint(authFailureHandler) //jwt认证失败处理
                .accessDeniedHandler(authDeniedHandler)
//                .and().logout().logoutSuccessHandler(logoutHandler) //登出过滤器
                .and().authorizeRequests()
                .antMatchers("/**/login", "/**/register", "/**/captchaImage", "/**/publicKey").anonymous() //未登录状态下可匿名访问
                .antMatchers("/webjars/**","/swagger-ui.html", "/swagger-resources/**", "/*/api-docs", "/doc.html", "/druid/**", "/**/captchaImage", "/**/publicKey", "/**/logout")
                .permitAll() //登陆或未登录状态下都可访问
                .anyRequest().authenticated(); // 其他所有接口认证后才可访问
        //jwtAuthenticationFilter过滤器在UsernamePasswordAuthenticationFilter过滤器之前执行, 进行用户访问认证
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        //先走跨域过滤器
        http.addFilterBefore(corsFilter.getFilter(), JwtAuthenticationFilter.class);
        return http.build();
    }
}